import React, { useState, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Table,
  Popconfirm,
  Divider,
  Button,
  Input,
  Space,
  Tag,
  Drawer,
  Checkbox,
} from 'antd';
import { PlusOutlined, SyncOutlined } from '@ant-design/icons';
import { connect, useIntl } from 'umi';
import moment from 'moment';
import ContentEdit from './components/contEdit';
import Categories from '@/pages/admin/categories';
import request from '@/utils/request';

const { Search } = Input;
const apiURL = '/api/services/app/Article/';

const ViewContent: React.FC<any> = (props) => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pageIndex, setPageIndex] = useState(1);
  const [pageSize] = useState(10);
  const [totalCount, setTotalCount] = useState(0);
  const [payload, setPayload] = useState({});
  const [id, setId] = useState(null);
  const [visible2, setVisible2] = useState(false);
  const intl = useIntl();

  useEffect(() => {
    fetchDatas();
  }, [pageIndex, payload]);

  const fetchDatas = () => {
    setLoading(true);
    request(apiURL + 'GetList', {
      method: 'Get',
      params: {
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        ...payload,
      },
    }).then((response) => {
      if (response && response.success) {
        var result = response.result;
        setDataSource(result.items);
        setTotalCount(result.totalCount);
      }
      setLoading(false);
    });
  };

  const handleDelete = (id: number) => {
    request(apiURL + 'Delete', {
      method: 'Delete',
      params: { id },
    }).then((response) => {
      if (response && response.success) {
        fetchDatas();
      }
    });
  };

  const handleAdd = () => {
    switchModal(true);
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys);
  };

  const onSearch = (value: any) => {
    setPayload({ ...payload, keywords: value });
  };

  const switchModal = (visible: boolean, id: any = null) => {
    setVisible(visible);
    setId(id);
  };

  const columns: any = [
    {
      title: intl.formatMessage({ id: 'pages.index' }),
      key: 'index',
      width: 60,
      render: (_: any, __: any, i: any) => {
        return i + 1;
      },
    },
    {
      title: intl.formatMessage({ id: 'pages.title' }),
      dataIndex: 'title',
      ellipsis: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.category' }),
      dataIndex: 'categoryName',
      width: 100,
      render: (text: string) => <span>{text}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.tags' }),
      dataIndex: 'tags',
      width: 120,
      render: (text: string) => <Tag color="lime">{text}</Tag>,
    },
    {
      title: intl.formatMessage({ id: 'pages.recommend' }),
      dataIndex: 'isRec',
      width: 80,
      render: (text: boolean) => <Checkbox checked={text} />,
    },
    {
      title: intl.formatMessage({ id: 'pages.publishTime' }),
      width: 200,
      dataIndex: 'creationTime',
      render: (text: string) => <span>{moment(text).format('YYYY-MM-DD HH:MM:SS')}</span>,
    },
    {
      title: intl.formatMessage({ id: 'pages.operation' }),
      render: (record: any) =>
        dataSource.length >= 1 ? (
          <span>
            <Popconfirm title={intl.formatMessage({ id: 'pages.confirmDelete' })} onConfirm={() => handleDelete(record.id)}>
              <a>{intl.formatMessage({ id: 'pages.delete' })}</a>
            </Popconfirm>
            <Divider type="vertical" />
            <a onClick={() => switchModal(true, record.id)}>{intl.formatMessage({ id: 'pages.edit' })}</a>
          </span>
        ) : null,
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Space>
          <Button
            type="primary"
            onClick={fetchDatas}
            loading={loading}
            icon={<SyncOutlined />}
          >
            {intl.formatMessage({ id: 'pages.refresh' })}
          </Button>
          <Button type="dashed" onClick={handleAdd} icon={<PlusOutlined />}>
            {intl.formatMessage({ id: 'pages.add' })}
          </Button>
          <Button type="dashed" onClick={() => setVisible2(true)}>
            {intl.formatMessage({ id: 'pages.addCategory' })}
          </Button>
          <Search
            placeholder={intl.formatMessage({ id: 'pages.searchPlaceholder' })}
            allowClear
            onSearch={(value) => onSearch(value)}
          />
          <span>{hasSelected ? intl.formatMessage({ id: 'pages.selectedItems' }, { count: selectedRowKeys.length }) : ''}</span>
        </Space>
      </Card>
      <Table
        rowKey="id"
        loading={loading}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={dataSource}
        pagination={{
          onChange: (page) => {
            setPageIndex(page);
          },
          pageSize,
          total: totalCount,
        }}
      />
      <Drawer
        width={600}
        placement="right"
        closable={false}
        onClose={() => setVisible2(false)}
        visible={visible2}
        destroyOnClose={true}
      >
        <Categories layout="article" />
      </Drawer>
      <Drawer
        width={1000}
        placement="right"
        closable={false}
        onClose={() => switchModal(false)}
        visible={visible}
        destroyOnClose={true}
      >
        <ContentEdit id={id} fetchDatas={fetchDatas} />
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(ViewContent);
